//
//  MainViewController.m
//  habit
//
//  Created by huck on 15-9-2.
//  Copyright (c) 2015年 custom. All rights reserved.
//

#import "MainViewController.h"
#import "MainUIStyleMng.h"
#import "MyHomeViewController.h"
#import "SuperviseViewController.h"
#import "TaskViewController.h"
#import "ProjectViewController.h"
#import "BaseNavigationController.h"
#import "AppDelegate.h"
#import "JSBadgeView.h"
#import "LoginAlertView.h"
#import "HomeManager.h"

@interface MainViewController ()<UIAlertViewDelegate>
{
    
    NSArray *titles;
    NSArray *navTitles;

    NSUInteger currentIndex;
    NSString *downloadUrl;
    NSString *versionNo;
    
    NSMutableArray *badgeValues; // tab数字提醒
    NSMutableArray *dotValues; // tab红点提醒
    UIView *menuView;
    UIView *maskView;

    UIBarButtonItem *menuBarButtonItem;
    UIBarButtonItem *addFriendBarButtonItem;
    
    NSString *currentLinkValue;
    UIWebView *phoneWebView;

    BOOL firstLoad;
    
    NSInteger beforeLoginAction;//登陆前将要去的页面,-1表示展示用户中心,其他的跳各自页面
}

@end

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    titles = [NSArray arrayWithObjects:@"首页", @"巡查", @"项目", @"任务", nil];
    navTitles = [NSArray arrayWithObjects:@"象山 • 剿劣", @"巡查督导", @"项目列表", @"我的任务", nil];

    [self initSubViews];
    [self registerNotification];
    [self requestSystemInfo];
    [self requestRegionInfo];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 如果直接放到viewDidLoad中执行初始化，ipad中红点和数字提醒位置会计算错误
    if (badgeValues == nil) {
        [self initBadgeViews];
    }
    if(beforeLoginAction>=0 && beforeLoginAction!=currentIndex &&[AppUtils isLogin]){
        [self setSelectedIndex:currentIndex];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!firstLoad) {
        [AppUtils checkAppUpdate];
        firstLoad = YES;
    }
    if(beforeLoginAction == -1 && [AppUtils isLogin]){
        [AppUtils showLeftViewController:YES];
        beforeLoginAction = currentIndex;
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

//启动后请求一些应用信息
-(void)requestSystemInfo
{
    NSArray *codes = @[SYS_INFO_waterClass,SYS_INFO_waterQuali,SYS_INFO_reanalysis,SYS_INFO_mascheme,SYS_INFO_proSort,SYS_INFO_proManage];
    for (NSString *code in codes) {
        [[HomeManager sharedInstance] requestAppSystemInfo:code complete:^(BOOL success) {}];
    }
}

//启动后请求乡镇信息
-(void)requestRegionInfo
{
    [[HomeManager sharedInstance] requestRegionInfo:^(BOOL success) {}];
}

//注册通知
- (void)registerNotification
{
    // 应用唤醒通知
    [AppUtils addObserver:self selector:@selector(onReceiveBecomActiveNotification:) name:XGBecomeActiveNotification];
    [AppUtils addObserver:self selector:@selector(onReceiveLoginOutNotification:) name:XGLoginOutSuccessNotification];

}

- (void)initSubViews
{
    [self initTabBarItems];
    self.selectedIndex = TabBarItemTypeHome;
    beforeLoginAction = TabBarItemTypeHome;
    
    maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MAIN_CONTENT_HEIGHT)];
    maskView.tag = 10000;
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.4;
    maskView.hidden = YES;
    [maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideQuickMenu)]];
    [self.view addSubview:maskView];
    
    self.delegate = self;
}


- (void)initTabBarItems
{
    UIFont *font = [UIFont systemFontOfSize:9];
    UIColor *tintColor = [UIColor colorWithString:COLOR_666666];
    NSDictionary *normalAttrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithString:COLOR_666666], NSForegroundColorAttributeName, font, NSFontAttributeName, nil];
    NSDictionary *selectedAttrs = [NSDictionary dictionaryWithObjectsAndKeys:tintColor, NSForegroundColorAttributeName, font, NSFontAttributeName, nil];

  MyHomeViewController *myHome = [[MyHomeViewController alloc]init];
    myHome.tabBarItem = [self getTabBarItem:titles[TabBarItemTypeHome] image:@"tab_home_nor" imageSel:@"tab_home_pre" normalAttrs:normalAttrs selectedAttrs:selectedAttrs tag:TabBarItemTypeHome];
    
    SuperviseViewController *group = [[SuperviseViewController alloc]init];
    group.tabBarItem = [self getTabBarItem:titles[TabBarItemTypeSupervise] image:@"tab_order_nor" imageSel:@"tab_order_pre" normalAttrs:normalAttrs selectedAttrs:selectedAttrs tag:TabBarItemTypeSupervise];
    
    ProjectViewController *squareView = [[ProjectViewController alloc] init];
    squareView.tabBarItem = [self getTabBarItem:titles[TabBarItemTypeProject] image:@"tab_message_nor" imageSel:@"tab_message_pre" normalAttrs:normalAttrs selectedAttrs:selectedAttrs tag:TabBarItemTypeProject];

    TaskViewController *settingView = [[TaskViewController alloc] init];
    settingView.tabBarItem = [self getTabBarItem:titles[TabBarItemTypeTask] image:@"tab_me_nor" imageSel:@"tab_me_pre" normalAttrs:normalAttrs selectedAttrs:selectedAttrs tag:TabBarItemTypeTask];
    
    self.viewControllers = [NSArray arrayWithObjects:myHome, group, squareView,settingView, nil];
    
    //设置图标和文字的样式
    [[MainUIStyleMng sharedInstance] setTabBarStyle:self.tabBar];
    [[MainUIStyleMng sharedInstance] setTabBarItemStyle:myHome.tabBarItem];
    [[MainUIStyleMng sharedInstance] setTabBarItemStyle:group.tabBarItem];
    [[MainUIStyleMng sharedInstance] setTabBarItemStyle:squareView.tabBarItem];
    [[MainUIStyleMng sharedInstance] setTabBarItemStyle:settingView.tabBarItem];
}


- (void)initBadgeViews
{
    badgeValues = [[NSMutableArray alloc] init];
    dotValues = [[NSMutableArray alloc] init];
    CGFloat itemWidth = 0;
    NSArray *subviews = self.tabBar.subviews;
    NSMutableArray *values = [[NSMutableArray alloc] init];
    for (UIView *view in subviews) {
        if (![view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            continue;
        }
        itemWidth = view.width;
        [values addObject:[NSNumber numberWithFloat:view.left]];
    }
    NSArray *offsetXs = [values sortedArrayUsingSelector:@selector(compare:)];
    UIView *itemView = nil;
    UIImageView *dotImgView = nil;
    JSBadgeView *badgeView = nil;
    for (NSNumber *offsetX in offsetXs) {
        itemView = [[UIView alloc] initWithFrame:CGRectMake(offsetX.floatValue, 0, itemWidth, 30)];
        itemView.userInteractionEnabled = NO;
        [self.tabBar addSubview:itemView];
        
        badgeView = [[JSBadgeView alloc] initWithParentView:itemView alignment:JSBadgeViewAlignmentCenter];
        badgeView.badgeTextFont = [UIFont systemFontOfSize:12.0];
//        badgeView.badgeText =@"1";
        badgeView.badgePositionAdjustment = CGPointMake(15, -5);
        [badgeValues addObject:badgeView];
        
        dotImgView = [[UIImageView alloc] initWithFrame:CGRectMake((itemWidth - 10) / 2 + 13, 3, 10, 10)];
        dotImgView.image = [UIImage imageNamed:@"reminder_bg_ones"];
        dotImgView.layer.cornerRadius = 5;
        dotImgView.layer.masksToBounds = YES;
        dotImgView.hidden = YES;
        [itemView addSubview:dotImgView];
        [dotValues addObject:dotImgView];
    }
}

#pragma mark 私有方法
//设置tabbarItem中的标题
- (UITabBarItem *)getTabBarItem:(NSString *)title image:(NSString *)image imageSel:(NSString *)imageSel normalAttrs:(NSDictionary *)normalAttrs selectedAttrs:(NSDictionary *)selectedAttrs tag:(NSInteger)tag
{
    UITabBarItem *barItem = [[UITabBarItem alloc] init];
    barItem.title = title;
    barItem.tag = tag;
    barItem.titlePositionAdjustment = UIOffsetMake(0, -4);
    return barItem;
}

//设置导航栏中各个模块的rightBtn
- (void)setRightButton:(NSInteger)tag
{
    switch (tag) {
        case TabBarItemTypeHome:
        case TabBarItemTypeSupervise:
        case TabBarItemTypeTask:
            //这个图片的颜色在[MainUIStyleMng setNavigationBarStyle]中的tintColor设置
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"user_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(selectorUserLogin)];
            break;
        case TabBarItemTypeProject:
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"project_list_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(showQuickMenu)];
            break;
        default:
            //其他的各自控制器上面直接设置
            self.navigationItem.rightBarButtonItem = nil;
    }
}

-(void)selectorUserLogin
{
    if (![AppUtils isLogin] ) {
        LoginAlertView *alert = [[LoginAlertView alloc] init];
        [alert show];
        beforeLoginAction = -1;
    }else{
        [AppUtils showLeftViewController:YES];
    }
}

/**
 * 显示快捷下拉菜单
 */
- (void)showQuickMenu
{
    NSArray *menus = [self getMenus];
    NSUInteger count = menus.count;
    if (menuView && menuView.hidden == NO) {
        [self hideQuickMenu];
        return;
    }
    if (nil == menuView) {
        menuView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 155, 2, 145, count * 25 + 8)];
        UIImage *bgImg = [[UIImage imageNamed:@"add_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(16, 6, 7, 41)];
        UIImageView *bg = [[UIImageView alloc]initWithFrame:menuView.bounds];
        bg.image = bgImg;
        [menuView addSubview:bg];
        [self.view addSubview:menuView];
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 8, 145, count * 25)];
        bgView.layer.cornerRadius = 3;
        bgView.layer.masksToBounds = YES;
        bgView.tag = 10;
        [menuView addSubview:bgView];
    }
    menuView.hidden = NO;
    maskView.hidden = NO;
    
    for (UIView *subviews in [[menuView viewWithTag:10] subviews]) {
        [subviews removeFromSuperview];
    }
    
    NSDictionary *menu = nil;
    UIColor *bgColor = [UIColor colorWithString:COLOR_666666];
    CGFloat y = 0;
    for (int i = 0; i < count; i++) {
        menu = menus[i];
        y = i * 25;
        BOOL addLine = i<count-1;
        [self createMenuItem:menu[@"tag"] icon:menu[@"icon"] title:menu[@"title"] y:y bgColor:bgColor addLine:addLine];
    }
}

- (void)hideQuickMenu
{
    maskView.hidden = YES;
    menuView.hidden = YES;
}

- (void)createMenuItem:(NSString *)tag icon:(NSString *)icon title:(NSString *)title y:(CGFloat)y bgColor:(UIColor *)bgColor addLine:(BOOL)addLine
{
    UIButton *view = [[UIButton alloc] initWithFrame:CGRectMake(0, y, 145, addLine ? 24.5 : 25)];
//    view.tag = [AppUtils toInteger:tag];
    view.accessibilityValue = tag;
    view.titleLabel.font = [UIFont systemFontOfSize:14];
    view.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    view.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [view setTitleColor:bgColor forState:UIControlStateNormal];
    [view setTitleColor:bgColor forState:UIControlStateHighlighted];
    [view setTitle:title forState:UIControlStateNormal];
    [view setTitle:title forState:UIControlStateHighlighted];
    [view setBackgroundImage:[UIColor imageWithColor:[UIColor colorWithString:COLOR_EDEEEF]]forState:UIControlStateNormal];
    [view setBackgroundImage:[UIColor imageWithColor:[UIColor colorWithString:COLOR_F7F8F9]] forState:UIControlStateHighlighted];
    [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMenuItem:)]];
    if(addLine){
        [AppUtils addSeparatorLine:[menuView viewWithTag:10] frame:CGRectMake(0, y+24.5, 145, 0.5) color:[UIColor colorWithString:COLOR_DBD9DE]];
    }
    [[menuView viewWithTag:10] addSubview:view];
}

- (NSArray *)getMenus
{
    NSMutableArray *values = [[NSMutableArray alloc] init];
    
    
    if(currentIndex == TabBarItemTypeProject) {
        for(SystemInfoData *data in [HomeManager sharedInstance].proSortList) {
            [values addObject:[self getMenuItem:data.systemValue title:data.systemLabel]];
        }
    }
    return values;
}

- (NSDictionary *)getMenuItem:(NSString *)typeId title:(NSString *)title
{
    return [NSDictionary dictionaryWithObjectsAndKeys:typeId, @"tag", title, @"title", nil];
}

//菜单点击
- (void)tapMenuItem:(UITapGestureRecognizer *)recognizer
{
    
    if(currentIndex == TabBarItemTypeProject){
      ProjectViewController *controller = [[self viewControllers] objectAtIndex: TabBarItemTypeProject];
        controller.projectTypeId = recognizer.view.accessibilityValue;
        [controller initData];
    }
    [self hideQuickMenu];
}

- (void)setBadgeValue:(TabBarItemType)tabBarItemType badgeValue:(NSInteger)badgeValue
{
    //以下代码模型，需要重新确认
    if (TabBarItemTypeHome == tabBarItemType || TabBarItemTypeSupervise == tabBarItemType) {
        UIImageView *dotImgView = [dotValues objectAtIndex:tabBarItemType];
        dotImgView.hidden = badgeValue != -1;
        return;
    }
    if (TabBarItemTypeProject == tabBarItemType ){
        JSBadgeView *badgeView = [badgeValues objectAtIndex:tabBarItemType];
        if (badgeValue >= 100) {
            badgeView.badgeText = @"99+";
        } else if (badgeValue <= 0) {
            badgeView.badgeText = nil;
        } else {
            badgeView.badgeText = [AppUtils toStr:badgeValue];
        }
    }
}

- (NSString *)getBadgeValue:(TabBarItemType)tabbarItemType
{
    JSBadgeView *badgeView = [badgeValues objectAtIndex:tabbarItemType];
    return badgeView.badgeText;
}

- (NSUInteger)getBadgeValueTotal
{
    NSUInteger total = 0;
    for (JSBadgeView *badgeView in badgeValues) {
        if ([AppUtils isNotEmpty:badgeView.badgeText]) {
            if ([badgeView.badgeText isEqualToString:@"99+"]) {
                total += 99;
            } else {
                total += [AppUtils toInteger:badgeView.badgeText];
            }
        }
    }
    return total;
}

#pragma mark action事件

/**
 * 接收应用唤醒通知
 */
- (void)onReceiveBecomActiveNotification:(NSNotification *)notification
{
}

/**
 * 接收用户退出通知
 */
- (void)onReceiveLoginOutNotification:(NSNotification *)notification
{
    if(currentIndex != TabBarItemTypeHome){
        [self setSelectedIndex:TabBarItemTypeHome];
    }
    [AppUtils showLeftViewController:NO];
}


#pragma mark UITabBarDelegate
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    beforeLoginAction = TabBarItemTypeHome; //保留前次页面
    currentIndex = item.tag;
    [[MainUIStyleMng sharedInstance] setNavigationItemTitleStyle:self.navigationItem titleIndex:item.tag title:navTitles[item.tag]];
    [self setRightButton:item.tag];
    [self hideQuickMenu];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(![AppUtils isLogin] && currentIndex != TabBarItemTypeHome){
        [[MainUIStyleMng sharedInstance] setNavigationItemTitleStyle:self.navigationItem titleIndex:beforeLoginAction title:navTitles[beforeLoginAction]];
        [self setRightButton:beforeLoginAction];
        LoginAlertView *alert = [[LoginAlertView alloc] init];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}

//程序跳转到指定页面
-(void)userSelectTab:(NSUInteger)tabIndex
{
    if(![AppUtils isLogin] && tabIndex != TabBarItemTypeHome){
        beforeLoginAction = TabBarItemTypeHome; //保留前次页面
        currentIndex = tabIndex;
        [[MainUIStyleMng sharedInstance] setNavigationItemTitleStyle:self.navigationItem titleIndex:beforeLoginAction title:navTitles[beforeLoginAction]];
        [self setRightButton:beforeLoginAction];
        LoginAlertView *alert = [[LoginAlertView alloc] init];
        [alert show];
        return;
    }else{
        [self setSelectedIndex:tabIndex];
    }
}

#pragma mark UITabBar Overwrite
- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [super setSelectedIndex:selectedIndex];
    currentIndex = selectedIndex;
    MainUIStyleMng * mainUIStyleMng = [MainUIStyleMng sharedInstance];
    [mainUIStyleMng setNavigationItemTitleStyle:self.navigationItem titleIndex:selectedIndex title:navTitles[selectedIndex]];
    [self setRightButton:selectedIndex];
}

-(TabBarItemType)getCurrentTabBarItemType
{
    return currentIndex;
}

@end
